<template>
  <el-dialog
      v-model="visible"
      :title="comment?.replyContent ? '修改回复' : '回复评论'"
      width="600px"
      @close="handleClose"
  >
    <div v-if="comment" class="reply-dialog">
      <!-- 评论信息 -->
      <div class="comment-info">
        <h4>原评论内容</h4>
        <div class="comment-content">
          <div class="comment-header">
            <span class="username">{{ comment.username }}</span>
            <el-rate
                v-model="comment.rating"
                disabled
                score-template="{value} 分"
                show-score
                text-color="#ff9900"
            />
          </div>
          <p class="content">{{ comment.content }}</p>
          <div v-if="comment.images && comment.images.length > 0" class="images">
            <el-image
                v-for="(image, index) in comment.images"
                :key="index"
                :preview-src-list="comment.images"
                :src="image"
                class="comment-image"
                fit="cover"
            />
          </div>
          <div class="comment-time">
            {{ formatDateTime(comment.createTime) }}
          </div>
        </div>
      </div>

      <!-- 回复表单 -->
      <div class="reply-form">
        <h4>{{ comment.replyContent ? '修改回复' : '商家回复' }}</h4>
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
        >
          <el-form-item label="回复内容" prop="replyContent">
            <el-input
                v-model="form.replyContent"
                :rows="4"
                maxlength="500"
                placeholder="请输入回复内容"
                show-word-limit
                type="textarea"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            :loading="loading"
            type="primary"
            @click="handleSubmit"
        >
          {{ comment?.replyContent ? '修改回复' : '发布回复' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {useCommentStore} from '@/store/comment'
import {formatDateTime} from '@/utils'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  comment: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// Store
const commentStore = useCommentStore()

// 响应式数据
const formRef = ref()
const loading = ref(false)

const form = reactive({
  replyContent: ''
})

const rules = {
  replyContent: [
    {required: true, message: '请输入回复内容', trigger: 'blur'},
    {min: 1, max: 500, message: '回复内容长度在 1 到 500 个字符', trigger: 'blur'}
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听评论变化，初始化表单
watch(() => props.comment, (newComment) => {
  if (newComment) {
    form.replyContent = newComment.replyContent || ''
  }
}, {immediate: true})

// 方法
const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  form.replyContent = ''
  formRef.value?.clearValidate()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    loading.value = true

    await commentStore.replyComment(props.comment.id, {
      replyContent: form.replyContent
    })

    ElMessage.success(props.comment.replyContent ? '修改回复成功' : '回复成功')
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('回复失败:', error)
      ElMessage.error('回复失败，请重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.reply-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

.comment-info {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.comment-info h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.comment-content {
  background: white;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-weight: 600;
  color: #409eff;
}

.content {
  margin: 8px 0;
  line-height: 1.6;
  color: #606266;
}

.images {
  display: flex;
  gap: 8px;
  margin: 8px 0;
  flex-wrap: wrap;
}

.comment-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.comment-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
}

.reply-form h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.dialog-footer {
  text-align: right;
}
</style>
